<template>
  <canvas-img ref="canv" :imgUrl="chooseImgSrc" @canvasFile="canvasFile"></canvas-img>
  <div class="change">
    <div class="change-box">
      <div class="change-box-avatar">
        <label for="avatar">头像：</label>
        <input @change="showPicture" type="file" id="avatar" ref="avatarInput" />
        <img :src="canvasSrc || userInfo.avatar" alt="" @click="chooseImg" />
      </div>
      <div class="change-box-realname">
        <label for="realname">昵称：</label>
        <input type="text" id="realname" v-model="newRealname" />
      </div>
      <div class="change-box-option">
        <button @click="uploadBaseInfo">更新</button>
        <button @click="cancelShow">取消</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import CanvasImg from './canvasImg.vue'
import { user } from '@/type/user'
import Message from '@/components/msg/msg'
import { ref, computed, onMounted, defineEmits } from 'vue'
import { useStore } from 'vuex'
import axios from '@/http'
const store = useStore()
const canv = ref<any>(null)
const imgFile = ref<File | null>(null)
const newRealname = ref<string>('')
const avatarInput = ref<HTMLInputElement | null>(null)
const chooseImgSrc = ref<string>('')
const canvasSrc = ref<string>('')
const emit = defineEmits(['cancelShowBaseChange'])
const userInfo = computed<user>(() => {
  return store.getters.user
})
onMounted(() => {
  newRealname.value = userInfo.value.realname
})
const chooseImg = () => {
  avatarInput.value?.click()
}
const canvasFile = (file: File) => {
  imgFile.value = file
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    const src = reader.result as string
    canvasSrc.value = src
    // 这里的reader.result就是文件的base64了。如果是图片的话，就能够间接放到src中展现了
  }
}
const uploadBaseInfo = () => {
  const { id } = userInfo.value
  const formData = new FormData()
  const avatarFile = imgFile.value ? imgFile.value : null
  if (avatarFile) {
    if (avatarFile.size / 1024 > 4000) {
      Message.error('文件大小不能超过4M')
      return
    }
    const avatarExtArr = avatarFile.type.split('/')
    const avatarExt = avatarExtArr[avatarExtArr.length - 1]
    if (!['jpg', 'png', 'jpeg', 'webp'].includes(avatarExt)) {
      Message.error('只能上传jpg,png,jpeg,webp格式的图片')
      return
    }
    formData.append('file', avatarFile)
  }
  formData.append('id', id + '')
  formData.append('realname', newRealname.value)
  axios
    .post('/user/update', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((res) => {
      if (res.data.error === -1) {
        if (avatarFile) {
          store.dispatch('setUserAvatar', res.data.data)
          avatarInput.value!.files = null
        }
        newRealname.value && store.dispatch('setUserRealName', newRealname.value)
        Message.success('更新成功')
        cancelShow()
      }
    })
}
const showPicture = () => {
  canv.value.showBack = true
  let url = window.webkitURL || window.URL
  let imgfileurl: string = ''
  if (avatarInput.value) imgfileurl = avatarInput.value.files ? url.createObjectURL(avatarInput.value.files[0]) : ''
  chooseImgSrc.value = imgfileurl
  avatarInput.value!.value = ''
}
const cancelShow = () => {
  emit('cancelShowBaseChange')
}
</script>

<style lang="scss" scoped>
.change {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 80px;
  margin: auto;
  background-color: #fff;
  width: 400px;
  height: 400px;
  border-radius: 5px;
  box-shadow: 0 0 6px 0 #8e8e8e;
  &-box {
    width: 200px;
    height: 200px;
    position: absolute;
    left: 0;
    right: 0;
    top: 0px;
    bottom: 0px;
    margin: auto;
    img {
      width: 45px;
      height: 45px;
      border-radius: 50%;
      vertical-align: middle;
    }
    #realname {
      border: none;
      border-bottom: 2px solid #000;
      margin: 10px;
      width: 180px;
    }
    #avatar {
      position: absolute;
      opacity: 0;
      z-index: -1;
    }
    label {
      margin: 0 10px;
      font-size: 14px;
      color: #8e8e8e;
    }
    &-realname {
      margin: 10px 0;
    }
    &-option {
      text-align: center;
      margin-top: 20px;
      button {
        width: 60px;
        height: 30px;
        margin: 8px 16px;
        border: none;
        &:hover {
          opacity: 0.6;
        }
        &:nth-child(2) {
          background-color: #d8d8d8;
        }
        &:nth-child(1) {
          background-color: #3d7bf2;
          color: #fff;
        }
      }
    }
  }
}
</style>
